<!-- components/FloatingButtons.vue -->
<template>
  <div
    class="floating-buttons"
    :class="{
      'show': showButtons,
      'expanded': isExpanded
    }"
    :style="{ bottom: bottomDistance }"
    @mouseenter="expandButtons"
    @mouseleave="collapseButtons"
  >
    <!-- 按钮组 -->
    <div class="button-group">
      <template v-for="(btn, index) in enabledButtons" :key="index">
        <button
          class="float-btn"
          :class="btn.type"
          v-show="btn.type !== 'backToTop' || showBackToTop"
          @click="handleClick(btn)"
          :title="btn.title"
        >
          <!-- 进度环（仅用于返回顶部按钮） -->
          <template v-if="btn.type === 'backToTop'">
            <svg class="progress-ring" :width="buttonSize" :height="buttonSize">
              <circle
                class="progress-ring__circle-bg"
                stroke="#eee"
                stroke-width="2"
                fill="transparent"
                :r="radius"
                :cx="buttonSize / 2"
                :cy="buttonSize / 2"
              />
              <circle
                class="progress-ring__circle"
                stroke="#60a5fa"
                stroke-width="2"
                fill="transparent"
                :r="radius"
                :cx="buttonSize / 2"
                :cy="buttonSize / 2"
                :stroke-dasharray="circumference"
                :stroke-dashoffset="dashOffset"
              />
            </svg>
          </template>

          <!-- 使用传入的图标组件 -->
          <component
            :is="btn.icon"
            class="icon"
            :class="{ 'with-progress': btn.type === 'backToTop' }"
            :width="20"
            :height="20"
          />
        </button>
      </template>
    </div>

    <!-- 主按钮/触发器 -->
    <button class="float-btn trigger-btn" title="工具栏">
      <PhList class="icon" :size="32" />
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue';
import type { Component } from 'vue';
import { defaultButtons } from '@/config/floatingButtons.ts';
import { PhList } from '@phosphor-icons/vue';

// 定义按钮配置接口
export interface ButtonConfig {
  type: string;
  title: string;
  icon: Component;
  onClick?: () => void;
  show?: boolean;
}

// 定义组件属性
interface Props {
  buttons?: ButtonConfig[];
}

const props = withDefaults(defineProps<Props>(), {
  buttons: () => defaultButtons
});

// 计算实际启用的按钮
const enabledButtons = computed(() =>
  props.buttons.filter(btn => btn.show !== false)
);

const showButtons = ref(false);
const showBackToTop = ref(false);
const progress = ref(0);
const isExpanded = ref(false);
const scrollThreshold = 300;

// 添加按钮尺寸的响应式处理
const isMobile = ref(false);
const buttonSize = computed(() => isMobile.value ? 36 : 40);
const radius = computed(() => buttonSize.value / 2 - 4); // 减去 4 是为了留出边距

// 更新圆环周长计算
const circumference = computed(() => 2 * Math.PI * radius.value);

// 计算圆环偏移量
const dashOffset = computed(() => {
  return circumference.value - (progress.value / 100) * circumference.value;
});

// 检查设备类型
const checkDevice = () => {
  isMobile.value = window.innerWidth <= 768;
};

// 展开/收起按钮组
const expandButtons = () => {
  isExpanded.value = true;
};

const collapseButtons = () => {
  isExpanded.value = false;
};

// 计算阅读进度
const calculateProgress = () => {
  const windowHeight = window.innerHeight;
  const documentHeight = document.documentElement.scrollHeight - windowHeight;
  const scrolled = window.scrollY;
  progress.value = Math.min(Math.round((scrolled / documentHeight) * 100), 100);
  showBackToTop.value = scrolled > scrollThreshold;
};
// 返回顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};
const handleClick = (btn: ButtonConfig) => {
  if (btn.type === 'backToTop') {
    scrollToTop();
  } else if (btn.onClick) {
    btn.onClick();
  }
};
// 节流函数
const throttle = (fn: Function, delay: number) => {
  let timer: NodeJS.Timeout | null = null;
  return () => {
    if (timer) return;
    timer = setTimeout(() => {
      fn();
      timer = null;
    }, delay);
  };
};

onMounted(() => {
  // 初始检查设备类型
  checkDevice();
  
  // 监听窗口大小变化
  window.addEventListener('resize', checkDevice);
  
  calculateProgress();
  const throttledScroll = throttle(calculateProgress, 100);
  window.addEventListener('scroll', throttledScroll);
  showButtons.value = true;

  // 添加 Intersection Observer 来监测页脚
  const footer = document.querySelector('footer');
  if (footer) {
    const observer = new IntersectionObserver(
      (entries) => {
        // 当页脚进入视口时
        bottomDistance.value = entries[0].isIntersecting ? '200px' : '40px';
      },
      {
        threshold: 0, // 只要有一个像素进入视口就触发
        rootMargin: '100px 0px 0px 0px' // 提前一点触发
      }
    );

    observer.observe(footer);

    // 清理观察器
    onUnmounted(() => {
      observer.disconnect();
    });
  }
});
onUnmounted(() => {
  window.removeEventListener('scroll', calculateProgress);
  window.removeEventListener('resize', checkDevice);
});
// 添加底部距离的 ref
const bottomDistance = ref('40px');
</script>

<style scoped lang="less">
.floating-buttons {
  position: fixed;
  right: 40px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  z-index: 999;
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  transition-property: all, bottom;

  &.show {
    opacity: 1;
    transform: translateY(0);
  }

  // 主按钮样式
  .trigger-btn {
    opacity: 0.6;
    transition: all 0.3s ease;
    order: 1; // 确保触发按钮在底部

    &:hover {
      opacity: 1;
      transform: rotate(180deg);
    }
  }

  // 按钮组
  .button-group {
    display: flex;
    flex-direction: column-reverse; // 反向排列，实现向上展开
    gap: 12px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    opacity: 0;
    transform: translateY(20px);
    pointer-events: none;
  }

  // 展开状态
  &.expanded {
    .button-group {
      opacity: 1;
      transform: translateY(0);
      pointer-events: auto;
    }

    .trigger-btn {
      opacity: 1;
      transform: rotate(180deg);
    }
  }

  .float-btn {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    background: white;
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #666;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    position: relative;

    &:hover {
      background: #60a5fa;
      color: white;
      transform: translateY(-2px);
      box-shadow: 0 6px 16px rgba(96, 165, 250, 0.2);
    }

    &:active {
      transform: translateY(0);
    }

    .progress-ring {
      position: absolute;
      top: 0;
      left: 0;
      transform: rotate(-90deg);
      width: 100%; // 确保 SVG 填满按钮
      height: 100%;

      &__circle-bg {
        opacity: 0.2;
      }

      &__circle {
        transition: stroke-dashoffset 0.1s ease;
      }
    }

    .icon {
      z-index: 1;
      width: 50%; // 图标大小相对于按钮的比例
      height: 50%;

      &.with-progress {
        z-index: 2;
      }
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .floating-buttons {
    right: 20px;

    .float-btn {
      width: 36px;
      height: 36px;

      .icon {
        width: 18px; // 手机上的图标尺寸
        height: 18px;
      }
    }
  }
}
</style>
